package com.tongda.core.utils;

import java.util.concurrent.atomic.AtomicInteger;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHelper extends SQLiteOpenHelper {

	public static DBHelper instance = null;
	
	private AtomicInteger mOpenCounter = new AtomicInteger(); 
	
	/** 数据库名称 **/
	public static final String DATABASE_NAME = "canyin-order-db.db";

	/** 数据库版本号 **/
	private static final int DATABASE_VERSION = 1;

	/** DB对象 **/
	SQLiteDatabase db = null;

	Context context = null;

	/** 数据库SQL语句 **/
	public static final String MESSAGE_TABLE_CREATE = "CREATE TABLE message ( id INTEGER PRIMARY KEY AUTOINCREMENT, name    VARCHAR( 60 )   DEFAULT ( '' ), [from]  VARCHAR( 60 )   DEFAULT ( '' ),type    INT             DEFAULT ( 0 ),call_type  INT DEFAULT ( 0 ), content BLOB DEFAULT ( 1 ), status  VARCHAR( 100 )  DEFAULT ( '' ),   [desc]  VARCHAR( 100 )  DEFAULT ( '' ),    mes_time  VARCHAR( 100 )  DEFAULT ( '' ), tabbleNo  VARCHAR( 100 )  DEFAULT ( '' ),serial_no  VARCHAR( 100 )  DEFAULT ( '' ),notificationId INT DEFAULT ( 0 ));";

	/** 菜肴表 建表SQL语句 **/
	public static final String DISH_TABLE_CREATE = "CREATE TABLE dish (id varchar(36) PRIMARY KEY,categoryId varchar(36),price integer,name varchar(32) NOT NULL,dishescode varchar(64),salenum integer,searchcode varchar(32),unitname varchar(32),isset varchar(32));";

	/** 菜肴分类表 建表SQL语句 **/
	public static final String DISH_CATEGORY_TABLE_CREATE = "CREATE TABLE dish_category(id varchar(36) PRIMARY KEY,name varchar(32) NOT NULL,code varchar(64), categoryLevel varchar(64),parentCategoryId varchar(64));";

	/** 菜肴分类排序表 建表SQL语句 **/
	public static final String ORDERDISH_CATEGORY_TABLE_CREATE = "CREATE TABLE orderdish_category(id varchar(36) PRIMARY KEY,count INTEGER);";

	
	public static synchronized DBHelper getInstance(Context context) {
		if (instance == null) {
			synchronized (context) {
				instance = new DBHelper(context);
			}
		}
		return instance;
	}

	public DBHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
		synchronized (context) {
			// 得到数据库对象
			db = openDatabase();
			this.context = context;
		}

	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL("DROP TABLE IF EXISTS message;");
		db.execSQL(MESSAGE_TABLE_CREATE);
		db.execSQL(DISH_TABLE_CREATE);
		db.execSQL(DISH_CATEGORY_TABLE_CREATE);
		db.execSQL(ORDERDISH_CATEGORY_TABLE_CREATE);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

	}
	public synchronized SQLiteDatabase openDatabase() {  
        if(mOpenCounter.incrementAndGet() == 1) {  
        	db = getWritableDatabase();  
        }  
        return db;  
    }  
  
    public synchronized void closeDatabase() {  
        if(mOpenCounter.decrementAndGet() == 0) {  
        	db.close();  
        }  
    } 
}
